package com.spzx.product.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.model.ProductSku;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.query.SkuQuery;
import com.spzx.product.service.*;
import com.spzx.product.vo.CategoryVo;
import com.spzx.product.vo.IndexDataVo;
import com.spzx.product.vo.ItemVo;
import com.spzx.product.vo.ProductSkuVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

@Tag(name = "聚合数据")
@RestController
@RequestMapping("/channel")
public class ChannelController extends BaseController {

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IProductSkuService productSkuService;

    @Autowired
    private ISkuStockService skuStockService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IProductDetailsService productDetailsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Operation(summary = "获取首页数据")
    @GetMapping("/index")
    public AjaxResult index() {
        //创建首页VO
        IndexDataVo indexDataVo = new IndexDataVo();
        //封装一级分类VO
        //获取一级分类数据
        List<CategoryVo> list1 = categoryService.getLevelOneCategory();
        indexDataVo.setCategoryList(list1);
        //封装TOP20商品列表VO
        //获取Top20商品VO
        List<ProductSkuVo> list2 = productSkuService.getTopSale();
        indexDataVo.setProductSkuList(list2);
        //响应VO
        return AjaxResult.success(indexDataVo);
    }

    @Operation(summary = "查询所有分类")
    @GetMapping("/category")
    public AjaxResult categoryList() {
        List<CategoryVo> categoryVoList = categoryService.tree();
        return AjaxResult.success(categoryVoList);
    }

    @Operation(summary = "分页查询商品列表")
    @GetMapping("/skuList/{pageNum}/{pageSize}")
    public TableDataInfo skuList(
            @Parameter(description = "当前页码")
            @PathVariable Integer pageNum,

            @Parameter(description = "每页记录数")
            @PathVariable Integer pageSize,

            SkuQuery skuQuery) {

        PageHelper.startPage(pageNum, pageSize);
        List<ProductSkuVo> list = productSkuService.selectProductSkuList(skuQuery);
        return getDataTable(list);
    }
    @Operation(summary = "封装商品SKU详情页所需数据")
    @GetMapping("/item/{skuId}")
    public AjaxResult item(@PathVariable("skuId") Long skuId){
        //解决缓存穿透问题：判断用户访问商品ID是否存在
        Boolean flag = redisTemplate.opsForValue().getBit("product:sku:data", skuId);
        if (!flag) {
            throw new ServiceException("访问商品不存在");
        }
        //创建ItemVo对象
        ItemVo itemVo = new ItemVo();
        //给ItemVo的七个属性赋值并返回
        //优化：：：：根据商品SKUID查询商品SKU信息  异步需要返回结果：商品SKU信息返回提供给 轮播图任务、详情图片任务、规格参数任务 使用
        CompletableFuture<Long> productIdCompletableFuture = CompletableFuture.supplyAsync(() -> {
            ProductSku skuInfo = productSkuService.getSkuInfo(skuId);
            //获取sku信息
            itemVo.setProductSku(skuInfo);
            return skuInfo.getProductId();
        });
        //获取商品sku价格,实时价格
        itemVo.setSkuPrice(productSkuService.getSkuPrice(skuId));
        //获取商品的库存信息
        itemVo.setSkuStock(skuStockService.getSkuStock(skuId));
        //查询商品轮播图列表,依赖于商品ID异步任务，不需要返回值
        CompletableFuture<Void> future = productIdCompletableFuture.thenAcceptAsync(productId -> {
            Product product = productService.getById(productId);
            if (product != null && StringUtils.isNoneBlank(product.getSliderUrls())) {
                String sliderUrls = product.getSliderUrls();
                itemVo.setSliderUrlList(sliderUrls.split(","));
            }
            //查询商品详情图片列表
//        productDetailsService.list(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId,productId));
            ProductDetails productDetails = productDetailsService.getOne(
                    new LambdaQueryWrapper<ProductDetails>()
                            .eq(ProductDetails::getProductId, productId)
            );
            if (productDetails != null && StringUtils.isNoneBlank(productDetails.getImageUrls())) {
                itemVo.setDetailsImageUrlList(productDetails.getImageUrls().split(","));
            }
            //查询商品规格信息，展示规格信息用于用户选择
            String specValue = product.getSpecValue();
            if (StringUtils.isNoneBlank(specValue)) {
                JSONArray jsonArray = JSON.parseArray(specValue);
                itemVo.setSpecValueList(jsonArray);
            }
            itemVo.setSkuSpecValueMap(productSkuService.getSkuSpecValue(productId));
        });

        //3.阻塞线程，等待所有任务完成
        CompletableFuture
                .allOf(
                        productIdCompletableFuture,
                        future)
                .join();

        return AjaxResult.success(itemVo);
    }

}